<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="父级分类id" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父级分类id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="祖级列表" prop="ancestors">
        <el-input
          v-model="queryParams.ancestors"
          placeholder="请输入祖级列表"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="简称" prop="alternativeName">
        <el-input
          v-model="queryParams.alternativeName"
          placeholder="请输入简称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="categoryCode">
        <el-input
          v-model="queryParams.categoryCode"
          placeholder="请输入编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="查询码" prop="lookup">
        <el-input
          v-model="queryParams.lookup"
          placeholder="请输入查询码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图片id" prop="pictureId">
        <el-input
          v-model="queryParams.pictureId"
          placeholder="请输入图片id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否已公开上架" prop="published">
        <el-input
          v-model="queryParams.published"
          placeholder="请输入是否已公开上架"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除标志" prop="deleted">
        <el-select v-model="queryParams.deleted" placeholder="请选择删除标志" clearable size="small">
          <el-option
            v-for="dict in deletedOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="显示顺序" prop="displayOrder">
        <el-input
          v-model="queryParams.displayOrder"
          placeholder="请输入显示顺序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建者" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable size="small"
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新者" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入更新者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable size="small"
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['catalog:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['catalog:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['catalog:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['catalog:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品分类id" align="center" prop="categoryId" />
      <el-table-column label="父级分类id" align="center" prop="parentId" />
      <el-table-column label="祖级列表" align="center" prop="ancestors" />
      <el-table-column label="名称" align="center" prop="categoryName" />
      <el-table-column label="简称" align="center" prop="alternativeName" />
      <el-table-column label="编码" align="center" prop="categoryCode" />
      <el-table-column label="查询码" align="center" prop="lookup" />
      <el-table-column label="图片id" align="center" prop="pictureId" />
      <el-table-column label="商品分类描述" align="center" prop="description" />
      <el-table-column label="是否已公开上架" align="center" prop="published" />
      <el-table-column label="删除标志" align="center" prop="deleted" :formatter="deletedFormat" />
      <el-table-column label="显示顺序" align="center" prop="displayOrder" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['catalog:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['catalog:category:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @open="openEditDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分类" prop="parentId">
          <!-- <el-input v-model="form.parentId" placeholder="请输入父级分类id" /> -->
          <!-- <el-cascader
            v-model="form.parentIds"
            :options="categoryTree"
            :props="categoryProps"
            @change="onChangeCategory"></el-cascader> -->
          <treeselect v-model="form.parentId" 
            :options="categoryTree" 
            :normalizer="normalizer" 
            @select="selectedParentCategory"
            placeholder="选择上级分类" />
        </el-form-item>
        <el-form-item label="名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="简称" prop="alternativeName">
          <el-input v-model="form.alternativeName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="编码" prop="categoryCode">
          <el-input v-model="form.categoryCode" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="查询码" prop="lookup">
          <el-input v-model="form.lookup" placeholder="请输入查询码" />
        </el-form-item>
        <el-form-item label="图片id" prop="pictureId">
          <el-input v-model="form.pictureId" placeholder="请输入图片id" />
        </el-form-item>
        <el-form-item label="商品分类描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否已公开上架" prop="published">
          <el-input v-model="form.published" placeholder="请输入是否已公开上架" />
        </el-form-item>
        <el-form-item label="删除标志">
          <el-radio-group v-model="form.deleted">
            <el-radio
              v-for="dict in deletedOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="displayOrder">
          <el-input v-model="form.displayOrder" placeholder="请输入显示顺序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, getCategoryTree,
  delCategory, addCategory, updateCategory, 
  exportCategory } from "@/api/catalog/category";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  
export default {
  name: "Category",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品分类表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标志字典
      deletedOptions: [],
      categoryTree: [],
      categoryProps: { 
        expandTrigger: 'hover',
        label: 'categoryName',
        value: 'categoryId',
        children: 'children',

      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        ancestors: null,
        categoryName: null,
        alternativeName: null,
        categoryCode: null,
        lookup: null,
        pictureId: null,
        description: null,
        published: null,
        deleted: null,
        displayOrder: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null
      },
      // 表单参数
      form: {
        parentIds: []
      },
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "商品分类id不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_show_hide").then(response => {
      this.deletedOptions = response.data;
    });
  },
  methods: {
    async getTree() {
      const categories = await getCategoryTree()
      // console.log('categories:', categories.data)
      for(let c of categories.data ) {
        if(c.children && c.children.length === 0){
          c.children = null;
        }
      }

      this.categoryTree = categories.data
    },
    openEditDialog () {
      this.getTree()
    },
    onChangeCategory(e) {
      // console.log('onChangeCategory', e)
      // console.log('this.form.parentIds select:', this.form.parentIds)

      this.form.ancestors = this.form.parentIds.toString()
            
    },
    normalizer(node, x) {
      // console.log('x', x)
      // console.log('node:', node)

      // if(node.children==null||node.children=='null'){
      //   delete node.children;
      // }
      if(!node.categoryId){
        return {
          id: null
        }
      }
      // console.log('node:', node)
      if (node.children && node.children.length === 0) {
        delete node.children;
      }
      if(node.children && node.children.length > 0) {
        return {
          id: node.categoryId,
          label: node.categoryName,
          ancestors: node.ancestors,
          children: node.children
        }
      } else {
        return {
          id: node.categoryId,
          label: node.categoryName,
          ancestors: node.ancestors
        }
      }
      // return {
      //   id: node.categoryId,
      //   label: node.categoryName,
      //   children: node.children //(node.children && !node.children.length) ? node.children : null
      // }
    },
    selectedParentCategory(node, instanceId) {
      // console.log('node:', node)
      // console.log('instanceId:', instanceId)
      if(node.ancestors){
        this.form.ancestors = node.ancestors + ',' + node.categoryId.toString()
      } else {
        this.form.ancestors = node.categoryId.toString()
      }
    },
    /** 查询商品分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 删除标志字典翻译
    deletedFormat(row, column) {
      return this.selectDictLabel(this.deletedOptions, row.deleted);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        parentId: null,
        parentIds: [],
        ancestors: null,
        categoryName: null,
        alternativeName: null,
        categoryCode: null,
        lookup: null,
        pictureId: null,
        description: null,
        published: null,
        deleted: 0,
        displayOrder: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId || this.ids
      getCategory(categoryId).then(response => {
        // console.log('this.form.parentIds update', this.form.parentIds)    
        // this.form.parentIds = []
        // this.form.parentIds.push(this.form.parentId)
        this.form = response.data;
        if(this.form.parentId === 0){
          this.form.parentId = null
        }
        this.open = true;
        this.title = "修改商品分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            // console.log('this.form.ParentIds:', this.form.parentIds)
            if(this.form.parentIds && this.form.parentIds.length > 0){
              // console.log('this.form.parentIds last', this.form.parentIds[this.form.parentIds.length - 1])
              this.form.ancestors = this.form.parentIds.toString()
            }
            
            updateCategory(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids;
      this.$confirm('是否确认删除商品分类编号为"' + categoryIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(categoryIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品分类数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCategory(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
